package com.pet.web.controller.system;

import com.pet.common.core.controller.BaseController;
import com.pet.common.core.domain.AjaxResult;
import com.pet.common.core.page.TableDataInfo;
import com.pet.common.utils.poi.ExcelUtil;
import com.pet.system.domain.PetProduct;
import com.pet.system.service.IPetProductService;
import com.pet.web.controller.system.vo.ProductBody;
import com.pet.web.controller.system.vo.ProductExcelBody;
import com.pet.web.controller.system.vo.ProductSelectBody;
import com.pet.web.controller.system.vo.ProductUpdateBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品Controller
 *
 * @author pet
 * @date 2022-10-09
 */
@Api(value = "商品管理", tags = "商品管理")
@RestController
@RequestMapping("/system/product")
public class PetProductController extends BaseController {
    @Autowired
    private IPetProductService petProductService;

    /**
     * 查询商品列表
     */
    @ApiOperation(value = "查询商品列表")
    @ApiImplicitParam(name = "productSelectBody", value = "productSelectBody", dataTypeClass = ProductSelectBody.class)
    @PreAuthorize("@ss.hasPermi('system:product:list')")
    @GetMapping("/list")
    public TableDataInfo list(ProductSelectBody productSelectBody) {
        startPage();
        PetProduct petProduct = new PetProduct();
        petProduct.setProductName(productSelectBody.getProductName());
        petProduct.setCategory(productSelectBody.getCategory());
        petProduct.setBrandName(productSelectBody.getBrandName());
        petProduct.setUserId(getUserId());
        List<PetProduct> list = petProductService.selectPetProductList(petProduct);
        return getDataTable(list);
    }

    /**
     * 导出商品模版
     */
    @ApiOperation(value = "导出商品模版")
    @PreAuthorize("@ss.hasPermi('system:product:export')")
    @GetMapping(value = "/export", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public void export(HttpServletResponse response) {
        //List<PetProduct> list = petProductService.selectPetProductList(petProduct);
        ExcelUtil<ProductExcelBody> util = new ExcelUtil<>(ProductExcelBody.class);
        util.exportExcel(response, new ArrayList<>(), "商品数据");
    }

    /**
     * 商品导入
     */
    @ApiOperation(value = "商品导入")
    @ApiImplicitParam(name = "file", value = "file", dataTypeClass = MultipartFile.class)
    @PreAuthorize("@ss.hasPermi('system:product:import')")
    @PostMapping(value = "/import", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult importProduct(@RequestPart("file") MultipartFile file) throws Exception {
        ExcelUtil<ProductExcelBody> util = new ExcelUtil<>(ProductExcelBody.class);
        List<ProductExcelBody> productExcelBodyList = util.importExcel(file.getInputStream());
        if (CollectionUtils.isEmpty(productExcelBodyList)) {
            return AjaxResult.error("导入商家数据不能为空");
        }
        List<ProductExcelBody> rightExcel = productExcelBodyList.stream().filter(e -> ObjectUtils.isNotEmpty(e)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(rightExcel)) {
            return AjaxResult.error("上传失败，请按照文件模版正确填写数据");
        }
        List<PetProduct> productList = new ArrayList<>();
        for (int i = 0; i < productExcelBodyList.size(); i++) {
            PetProduct petProduct = new PetProduct();
            BeanUtils.copyProperties(productExcelBodyList.get(i), petProduct);
            petProduct.setUserId(getUserId());
            productList.add(petProduct);
        }
        return petProductService.importProduct(productList, getUserId());
    }

    /**
     * 获取商品详细信息
     */
    @ApiOperation(value = "获取商品详细信息")
    @PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(petProductService.selectPetProductById(id));
    }

    /**
     * 新增商品
     */
    @ApiOperation(value = "新增商品")
    @ApiImplicitParam(name = "productBody", value = "productBody", dataTypeClass = ProductBody.class)
    @PreAuthorize("@ss.hasPermi('system:product:add')")
    @PostMapping
    public AjaxResult add(@RequestBody ProductBody productBody) {
        if (StringUtils.isBlank(productBody.getProductName()) &&
                null != productBody.getBrandId() &&
                StringUtils.isBlank(productBody.getCategory()) &&
                StringUtils.isBlank(productBody.getBrandName())) {
            return AjaxResult.error("类目、品牌(id和名称)、商品名称均不可为空！");
        }
        PetProduct petProduct = new PetProduct();
        BeanUtils.copyProperties(productBody, petProduct);
        petProduct.setUserId(getUserId());
        return toAjax(petProductService.insertPetProduct(petProduct));
    }

    /**
     * 修改商品
     */
    @ApiOperation(value = "修改商品")
    @ApiImplicitParam(name = "productUpdateBody", value = "productUpdateBody", dataTypeClass = ProductUpdateBody.class)
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody ProductUpdateBody productUpdateBody) {
        PetProduct petProduct = new PetProduct();
        petProduct.setId(productUpdateBody.getId());
        petProduct.setSpec(productUpdateBody.getSpec());
        petProduct.setTradePrice(productUpdateBody.getTradePrice());
        petProduct.setRetailPrice(productUpdateBody.getRetailPrice());
        petProduct.setPromotion(productUpdateBody.getPromotion());
        return toAjax(petProductService.updatePetProduct(petProduct));
    }

    @ApiOperation(value = "上传商品图片")
    @PreAuthorize("@ss.hasPermi('system:product:edit')")
    @PostMapping(value = "/uploadImage", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public AjaxResult uploadImage(@ApiParam(name = "image", value = "图片文件", required = true) @RequestPart("image") MultipartFile image,
                                  @ApiParam(name = "id", value = "id", required = true) @RequestParam("id") Long id) throws IOException {
        PetProduct petProduct = new PetProduct();
        petProduct.setId(id);
        petProduct.setImage(image.getBytes());
        return toAjax(petProductService.updatePetProductImage(petProduct));
    }

    @ApiOperation(value = "下载商品图片")
    @PreAuthorize("@ss.hasPermi('system:product:query')")
    @GetMapping("/downloadImage/{id}")
    public AjaxResult downloadImage(@PathVariable("id") Long id, HttpServletResponse response) {
        PetProduct petProduct = petProductService.selectPetProductById(id);
        if (null == petProduct.getImage() || 0 == petProduct.getImage().length) {
            return AjaxResult.success("产品暂无图片");
        }
        InputStream inputStream = new ByteArrayInputStream(petProduct.getImage());
        response.setContentType("image/*");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = inputStream.read(buffer, 0, 1024)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 删除商品
     */
    @ApiOperation(value = "删除商品")
    @PreAuthorize("@ss.hasPermi('system:product:remove')")
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(petProductService.deletePetProductById(id));
    }
}
